package br.com.senac.digipao.servlet;

import br.com.senac.digipao.bean.Usuario;
import br.com.senac.digipao.dao.UsuarioDao;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "LogInServlet", urlPatterns = {"/LogInServlet"})
public class LogInServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String login = request.getParameter("login");
        String senha = request.getParameter("senha");

        try {
            UsuarioDao dao = new UsuarioDao();
            Usuario usuario = dao.autentica(login, senha);

            if(usuario.getLogin() == null){
                RequestDispatcher rd = request.getRequestDispatcher("/media/jsp/falhaNaAutenticacao.jsp");
                rd.forward(request, response);
            } else {
                request.getSession().setAttribute("Usuario", usuario);
                Usuario alteraUsuario = (Usuario) request.getSession(true).getAttribute("Usuario");
               
                if (alteraUsuario == null) {
                    RequestDispatcher rd = request.getRequestDispatcher("/media/jsp/menuPrincipal.jsp");
                    rd.forward(request, response);
                } else {
                   RequestDispatcher rd = request.getRequestDispatcher("/media/jsp/menuPrincipal.jsp");
                   rd.forward(request, response);
                } 
            }
        } catch (SQLException ex) {
            Logger.getLogger(LogInServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}